﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SocialIn.Biz;
using System.IO;
using System.Configuration;

namespace SocialIn.Web.Members
{
    public partial class ProfileImageUp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session[ConfigName.SessionMember] == null)
            {
                string script = "<script>window.close();</script>";
                Response.Write(script);
                Response.End();
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            string filetype = Path.GetExtension(fileup.FileName);
            if (!CheckFileType(filetype))
            {
                AlertMessage(" PNG, JPG, GIF 파일만 업로드 가능합니다.");
                return;
            }
            
            string userid = (HttpContext.Current.Session[ConfigName.SessionMember] as Member).UserID;
            string savefilename = GetFileName(filetype);
            try
            {
                fileup.SaveAs(Path.Combine(ConfigurationManager.AppSettings["FILEUPPATH"].ToString(), savefilename));
                Join j = new Join();
                string savefname = string.Format("/stroage/member/{0}", savefilename);
                j.UpDateProFileImage(userid, savefname);

                ltrscript.Text = string.Format("<script>SaveOK('{0}');</script>", savefname);
            }
            catch(Exception ex){
                AlertMessage("파일 저장에 실패했습니다. 다시 시도해주세요!");
            }


        }

        private string GetFileName(string filetype)
        {
            string fname = string.Format("{0}{1}", DateTime.Now.Ticks.ToString(), filetype);
            return fname;
        }

        /// <summary>
        /// 이미지 확장자가 유효한지 체크합니다.
        /// ( .png, .jpeg, .jpg)
        /// </summary>
        /// <param name="ftype"></param>
        /// <returns></returns>
        public bool CheckFileType(string ftype)
        {
            bool fileOk = false;
            ftype = ftype.ToLower();
            string[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };

            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (ftype == allowedExtensions[i])
                    fileOk = true;
            }

            return fileOk;
        }

        private void AlertMessage(string message)
        {
            message = string.Format("<script language=javascript>alert('{0}');</script>", message);
            ClientScript.RegisterClientScriptBlock(this.GetType(), "message", message);
        }
    }
}